/**
 * 物料分类
 * @author Canaan
 * @date 2019/8/14 14:28
 */
export default {

  state: {
    materialCategoryOptions: {
      loading: false,     //数据是否加载中
      options: []         //具体的选项列表
    }
  },

  actions: {

    reloadMaterialCategoryOptions({commit, state}, vue) {
      //如果正在加，就不处理
      if (state.materialCategoryOptions.loading) {
        return;
      }

      commit('materialCategoryOptions', {cmd: "loading", val: true});

      return vue.$ajax.get('material_category/tree')
        .then(res => {
          commit('materialCategoryOptions', {cmd: "loading", val: false});
          if (res.code !== 'ok') {
            throw res.msg;
          }
          commit('materialCategoryOptions', {cmd: "options", val: res.data.rows || []});
        });

    },
    loadMaterialCategoryOptions({commit, state, dispatch}, vue) {

      //如果正在加，就不处理
      if (state.materialCategoryOptions.loading) {
        return;
      }

      //如果有数据就不加载
      if (state.materialCategoryOptions.options.length > 0) {
        return;
      }

      dispatch('reloadMaterialCategoryOptions', vue);

    }
  },

  mutations: {
    /**
     *  清空数据
     */
    clearMaterialCategoryOptions({materialCategoryOptions}) {
      materialCategoryOptions.options = [];
    },
    materialCategoryOptions({materialCategoryOptions}, {cmd, val}) {

      switch (cmd) {
        case "loading":
          materialCategoryOptions.loading = val;
          break;
        case "options":
          materialCategoryOptions.options = val;
          break;
        default:
          throw "materialCategoryOptions 未知的命令" + cmd;
      }

    }

  },

  getters: {
    /**
     * 根据父级分类，获取子分类。如果父级分类为空，就返回顶级分类
     * @author Canaan
     * @date 2019/8/29 16:33
     */
    getMaterialCategoryByParent: (state, getters) => {

      function recursionChild(arr, id) {
        if (!arr || arr.length === 0) {
          return null;
        }

        for (let item of arr) {
          if (!item) {
            continue;
          }
          if (item.id === id) {
            return item;
          }
          let result = recursionChild(item.child, id);
          if (result) {
            return result;
          }
        }
        return null;
      }

      return (parentId) => {

        if (!parentId) {
          //查询顶级节点
          return state.materialCategoryOptions.options;
        }

        for (let option of state.materialCategoryOptions.options) {
          if (!option) {
            continue;
          }
          if (option.id === parentId) {
            return option.child || [];
          }
          let result = recursionChild(option.child, parentId);
          if (result) {
            return result.child || [];
          }
        }

        return [];
      };

    }
  }

}
